package com.clp.protocol.iec104.iec104.client;

import com.clp.protocol.core.pdu.PduRecvCallback;
import com.clp.protocol.iec104.iec104.apdu.Apdu;

import java.util.Collection;
import java.util.Vector;

public class InMasterApduRecver implements MasterApduRecver {
    private final InMaster inMaster;

    // 回调列表
    private final Vector<PduRecvCallback<Apdu>> frameRecvCallbacks = new Vector<>();

    public InMasterApduRecver(InMaster inMaster) {
        this.inMaster = inMaster;
    }

    @Override
    public void addRecvCallback(PduRecvCallback<Apdu> callback) {
        this.frameRecvCallbacks.add(callback);
    }

    @Override
    public void addRecvCallbacks(Collection<PduRecvCallback<Apdu>> frameRecvCallbacks) {
        this.frameRecvCallbacks.addAll(frameRecvCallbacks);
    }

    @Override
    public void removeRecvCallback(PduRecvCallback<Apdu> callback) {
        this.frameRecvCallbacks.remove(callback);
    }

    @Override
    public void removeRecvCallbacks(Collection<PduRecvCallback<Apdu>> frameRecvCallbacks) {
        this.frameRecvCallbacks.removeAll(frameRecvCallbacks);
    }

    public void handleRecvCallbacks(Apdu apdu) {
        inMaster.getAsyncSupport().scheduledExecutorService().submit(() -> {
            try {
                this.frameRecvCallbacks.removeIf(callback -> callback.whenRecv(apdu));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
